package defiam

import (
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain/iam/store"
	kvs "git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain/keyvaluestore"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain_sdk/provider/iampvdr"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/core"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/iam"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/ichain"
	"github.com/pkg/errors"
)

// ProviderFactory 创建iam
type ProviderFactory struct {
}

func NewProviderFactory() *ProviderFactory {
	f := ProviderFactory{}
	return &f
}

// CreateUserStore 创建用户数据存储
func (f *ProviderFactory) CreateUserStore(config iam.IdentityConfig) (iam.UserStore, error) {
	stateStorePath := config.CredentialStorePath()

	var userStore iam.UserStore
	if stateStorePath == "" {
		return store.NewMemoryUserStore(), nil
	}

	stateStore, err := kvs.New(&kvs.FileKeyValueStoreOptions{Path: stateStorePath})
	if err != nil {
		return nil, errors.WithMessage(err, "CreateNewFileKeyValueStore failed")
	}
	userStore, err = store.NewCertFileUserStore(stateStore)
	if err != nil {
		return nil, errors.Wrapf(err, "creating a user store failed")
	}

	return userStore, nil
}

// CreateIdentityManagerProvider 创建身份管理
func (f *ProviderFactory) CreateIdentityManagerProvider(endpointConfig ichain.EndpointConfig, cryptoProvider core.CryptoSuite, userStore iam.UserStore) (iam.IdentityManagerProvider, error) {
	return iampvdr.New(endpointConfig, cryptoProvider, userStore)
}
